package net.tarine.gastronomi.client.forms;

import net.tarine.gastronomi.client.AuthSingleton;
import net.tarine.gastronomi.client.IAuthenticatedWidget;
import net.tarine.gastronomi.client.ParamMap;
import net.tarine.gastronomi.client.UiSingleton;
import net.tarine.gastronomi.client.WaitSingleton;
import net.tarine.gastronomi.client.services.GasService;
import net.tarine.gastronomi.client.services.GasServiceAsync;
import net.tarine.gastronomi.client.widgets.FramePanel;
import net.tarine.gastronomi.shared.AppConst;
import net.tarine.gastronomi.shared.Role;
import net.tarine.gastronomi.shared.ValidationException;
import net.tarine.gastronomi.shared.to.GasTo;
import net.tarine.gastronomi.shared.to.GasUserTo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

public class GasEditPage extends FramePanel implements IAuthenticatedWidget, ChangeHandler {

	private GasServiceAsync gasService = GWT.create(GasService.class);
	
	private String gasId = null;
	private GasTo item = null;
	private boolean editable = false;
	
	private TextBox nameText = null;
	private TextBox smtpText = null;
	private TextBox emailText = null;
	private PasswordTextBox pass1Text = null;
	private PasswordTextBox pass2Text = null;
	private FlowPanel imgPanel = null;
	private Image okImg = null;
	private Image koImg = null;
	
	private final AsyncCallback<GasTo> callback = new AsyncCallback<GasTo>() {
		@Override
		public void onFailure(Throwable caught) {
			UiSingleton.get().addError(caught);
			WaitSingleton.get().stop();
		}
		@Override
		public void onSuccess(GasTo result) {
			item =result;
			UiSingleton.get().setGas(item);
			draw();
			WaitSingleton.get().stop();
		}
	};
	
	public GasEditPage(ParamMap params) {
		if (params != null) {
			gasId = params.getValue(AppConst.PARAM_ID);
		}
		AuthSingleton.get().authorizeWidget(this);
	}
	@Override
	public void unlockWidget(GasUserTo user) {
		if (user.getRoleId().intValue() == Role.ADMIN.getId()) editable = true;
		if (gasId == null) gasId = user.getGasId();
		if (gasId == null) gasId = AppConst.NEW_ITEM_ID;
		okImg = new Image("img/check-green.png");
		koImg = new Image("img/fail-red.png");
		loadGas();
	}
	
	private void draw() {
		this.clear();
		final FormPanel form = new FormPanel();
		FlexTable table = new FlexTable();
		form.add(table);
		int r=0;
			
		//Name
		table.setHTML(r, 0, "Nome");
		nameText = new TextBox();
		nameText.setValue(item.getName());
		nameText.setMaxLength(32);
		nameText.setEnabled(editable);
		table.setWidget(r, 1, nameText);
		table.getFlexCellFormatter().setColSpan(r, 1, 4);
		r++;
		
		//Instructions
		table.setHTML(r, 0, "Lasciando vuoti i campi sottostanti sarà impossibile l'invio delle email");
		table.getFlexCellFormatter().setColSpan(r, 0, 5);
		r++;
		
		//Smtp
		table.setHTML(r, 0, "Server smtp");
		smtpText = new TextBox();
		smtpText.setValue(item.getEmailSmtp());
		smtpText.setEnabled(editable);
		table.setWidget(r, 1, smtpText);
		//Email
		table.setHTML(r, 3, "Email mittente");
		emailText = new TextBox();
		emailText.setValue(item.getEmailAddress());
		emailText.setEnabled(editable);
		table.setWidget(r, 4, emailText);
		r++;
		
		//Pass1
		table.setHTML(r, 0, "Password");
		pass1Text = new PasswordTextBox();
		pass1Text.setEnabled(editable);
		pass1Text.addChangeHandler(this);
		table.setWidget(r, 1, pass1Text);
		//Pass2
		table.setHTML(r, 3, "Ripeti la password");
		pass2Text = new PasswordTextBox();
		pass2Text.setEnabled(editable);
		pass2Text.addChangeHandler(this);
		table.setWidget(r, 4, pass2Text);
		//Password image
		imgPanel = new FlowPanel();
		table.setWidget(r, 5, imgPanel);
		r++;
		
		HorizontalPanel buttonPanel = new HorizontalPanel();
		// Bottone SALVA
		Button submitButton = new Button("Salva", new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				form.submit();
			}
		});
		if (item.getId() == null) {
			submitButton.setText("Crea");
		}
		submitButton.setEnabled(editable);
		buttonPanel.add(submitButton);
		
		table.setWidget(r,0,buttonPanel);
		table.getFlexCellFormatter().setColSpan(r, 0, 5);
		
		form.addSubmitHandler(new SubmitHandler() {
			@Override
			public void onSubmit(SubmitEvent event) {
				try {
					saveGas();
				} catch (ValidationException e) {
					UiSingleton.get().addWarning(e.getMessage());
				}
			}
		});
		String title = "Impostazioni nuovo gas";
		if (item.getName() != null) title = "Impostazioni \""+item.getName()+"\"";
		this.set(form, title);
	}
	
	@Override
	public void onChange(ChangeEvent event) {
		String p1 = pass1Text.getValue();
		String p2 = pass2Text.getValue();
		if (p1.equals("") && p2.equals("")) {
			imgPanel.clear();
			imgPanel.add(koImg);
			return;
		}
		if (p1.equals(p2)) {
			imgPanel.clear();
			imgPanel.add(okImg);
		} else {
			imgPanel.clear();
			imgPanel.add(koImg);
		}
	}
	
	
	
	//Async methods
	
	
	
	private void loadGas() {
		if (gasId.equals(AppConst.NEW_ITEM_ID)) {
			item = new GasTo();
			draw();
		} else {
			WaitSingleton.get().start();
			gasService.findGas(callback);
		}
	}

	private void saveGas() throws ValidationException {
		WaitSingleton.get().start();
		//validation
		if (nameText.getValue() == null) throw new ValidationException("Il nome non puo' essere vuoto");
		if (nameText.getValue().length() < 2) throw new ValidationException("Il nome non puo' essere vuoto");
		item.setName(nameText.getValue());
		item.setEmailAddress(emailText.getValue());
		item.setEmailPassword(pass1Text.getValue());
		item.setEmailSmtp(smtpText.getValue());
		gasService.persistGas(item, callback);
	}
}
